package com.xkstream.client.presenter;

import com.google.gson.Gson;
import com.xkstream.client.api.UserApi;
import com.xkstream.client.api.UserService;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.BasePresenterImpl;
import com.xkstream.client.entity.User;
import com.xkstream.client.rx.RxHelper;
import com.xkstream.client.rx.RxObserver;
import com.xkstream.client.utils.PreferenceUtils;

import java.util.Map;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xiaoyi on 2017-8-28.
 */

public class RegisterPresenterV2 extends BasePresenterImpl implements RegisterContractV2.Presenter {
    private RegisterContractV2.View view;
    private UserService userService;

    public RegisterPresenterV2(RegisterContractV2.View view) {
        this.view = view;
        this.view.setPresenter(this);
        userService = UserApi.getInstance().service;
    }

    @Override
    public void anchorRegister(Map<String, Object> params) {
        view.showLoading();
        userService.anchorRegisterV2(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .flatMap(baseData -> {
                    if (baseData.getCode() == 1) {
                        return userService.userLogin(params);
                    } else {
                        view.registerFailed(baseData.getCode(), baseData.getMsg());
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new RxObserver<BaseData<User>>(this) {
            @Override
            protected void onSuccess(BaseData<User> userBaseData) {
                view.hideLoading();
                if (userBaseData.getCode() == 1) {
                    PreferenceUtils.putString(PreferenceUtils.USER,
                            new Gson().toJson(userBaseData.getData()));
                    Application.setUser(userBaseData.getData());
                    view.loginSuccess(userBaseData.getData());
                }
            }

            @Override
            protected void onFail(String message) {
                view.hideLoading();
            }
        });

    }


}
